package dacp.etl.kafka.hdfs.connect.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.math.RandomUtils;

public class NameReplace {

	private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{(\\w+)(%\\d+\\w)?\\}");

	public static String replace(String fmt, Map<String, String> res) {
		
		res.put("random", RandomUtils.nextInt(99999999)+"");
		
		Matcher matcher = VARIABLE_PATTERN.matcher(fmt);
		String result = fmt;
		while (matcher.find()) {
			String variable = matcher.group(1);
			String houzui = matcher.group(2);
			String val = matcher.group();
			if(houzui == null){
				val = res.get(variable);
			}else{ 
				val = String.format(houzui, Integer.valueOf(res.get(variable)));
			}
			result = result.replace(matcher.group(), val);
 		}
		return result;
	}
	 
	
	
	public static void main(String[] args) {
		Map<String, String> mapping = new HashMap<String, String>();
		
		mapping.put("xxxx", "001");
		mapping.put("aaa", "2");
		
		System.out.println(replace("aaaaa{xxxx}{random%010d}", mapping));
	}

}
